package com.runen.infinitemovement.widget.popupwind;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.MemberListAdapter;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.entity.AllTeamGroupUserEntity;
import com.runen.infinitemovement.model.entity.MemberEntity;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HandOverTeamPoppupWindow extends PopupWindow {
    private ImageView iv_dismiss;
    private TextView tv_member_num, tv_sure, tv_over;
    private RecyclerView rv_member_list_info;
    private EditText edt_input_search;
    private Context context;
    private View layout;
    private MemberListAdapter memberListAdapter;
    private List<MemberEntity.DataBean.TeamMemberListBean> memberListBean;
    private List<MemberEntity.DataBean.TeamMemberListBean> searchMemberListBean;
    private String num = "全部成员（%s）";
    private String leaderId;
    private String headerUrl;
    private String userName;
    private String companyId;
    private int type = 0;//1:移交军团长；2：管理军团成员
    public static final int TYPE_TRANSFER = 1;
    public static final int TYPE_MANAGER = 2;
    private KickOut kickOut;

    public OnHandOverListener getOnHandOverListener() {
        return onHandOverListener;
    }

    public void setOnHandOverListener(OnHandOverListener onHandOverListener) {
        this.onHandOverListener = onHandOverListener;
    }

    public void setKickOut(KickOut kickOut) {
        this.kickOut = kickOut;
    }

    private OnHandOverListener onHandOverListener;

    public static HandOverTeamPoppupWindow getInstance(Context context, List<MemberEntity.DataBean.TeamMemberListBean> memberListBean) {
        return new HandOverTeamPoppupWindow(context, memberListBean, 0);
    }

    public static HandOverTeamPoppupWindow getInstance(Context context, List<MemberEntity.DataBean.TeamMemberListBean> memberListBean, int type) {
        return new HandOverTeamPoppupWindow(context, memberListBean, type);
    }

    public static HandOverTeamPoppupWindow getInstances(Context context,
                                                        List<AllTeamGroupUserEntity.DataBean> tenantListBeans,
                                                        String companyId) {
        return getInstances(context, tenantListBeans, companyId, TYPE_TRANSFER);
    }

    /**
     * 移交军团长
     *
     * @param context
     * @param tenantListBeans
     * @param type            1:移交军团长；2：管理军团成员
     * @return
     */
    public static HandOverTeamPoppupWindow getInstances(Context context,
                                                        List<AllTeamGroupUserEntity.DataBean> tenantListBeans,
                                                        String companyId, int type) {
        List<MemberEntity.DataBean.TeamMemberListBean> memberListBean = new ArrayList<>();
        for (AllTeamGroupUserEntity.DataBean tenant : tenantListBeans) {
            MemberEntity.DataBean.TeamMemberListBean teamMemberBean = new MemberEntity.DataBean.TeamMemberListBean();
            teamMemberBean.headImgUrl = tenant.headImgUrl;
            teamMemberBean.nickname = tenant.nickName;
            teamMemberBean.userId = tenant.userId;
            teamMemberBean.createTime = tenant.createTime;
            teamMemberBean.tinder = tenant.totalTinder;
            memberListBean.add(teamMemberBean);
        }
        return new HandOverTeamPoppupWindow(context, memberListBean, type, companyId);
    }

    private HandOverTeamPoppupWindow(Context context, List<MemberEntity.DataBean.TeamMemberListBean> memberListBean, int type) {
        super(context);
        this.context = context;
        this.memberListBean = memberListBean;
        this.type = type;
        initView();
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //this.setHeight((int) (CommonUtil.getScreenHW((Activity) context)[1] / 3));
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        // 这样设置才能点击屏幕外dismiss窗口
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setContentView(layout);

        initEvent();
    }

    private HandOverTeamPoppupWindow(Context context, List<MemberEntity.DataBean.TeamMemberListBean> memberListBean,
                                     int type, String companyId) {
        super(context);
        this.context = context;
        this.memberListBean = memberListBean;
        this.type = type;
        this.companyId = companyId;
        initView();
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //this.setHeight((int) (CommonUtil.getScreenHW((Activity) context)[1] / 3));
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        // 这样设置才能点击屏幕外dismiss窗口
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setContentView(layout);

        initEvent();
    }

    private void initView() {
        searchMemberListBean = new ArrayList<>();
        layout = View.inflate(context, R.layout.popup_hand_over_team, null);
        iv_dismiss = layout.findViewById(R.id.iv_dismiss);
        tv_over = layout.findViewById(R.id.tv_over);
        edt_input_search = layout.findViewById(R.id.edt_input_search);
        edt_input_search.setVisibility(type == TYPE_TRANSFER ? View.VISIBLE : View.GONE);

        tv_member_num = layout.findViewById(R.id.tv_member_num);
        rv_member_list_info = layout.findViewById(R.id.rv_member_list_info);
        tv_sure = layout.findViewById(R.id.tv_sure);
        tv_over.setText(type == TYPE_TRANSFER ? "移交军团长给队员" : type == 0 ? "移交队长给队员" : "管理队员");
        tv_sure.setText(type == TYPE_MANAGER ? "踢出队伍" : "移交");

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_member_list_info.setLayoutManager(layoutManager);
        memberListAdapter = new MemberListAdapter(context, 2);
        rv_member_list_info.setAdapter(memberListAdapter);
        if (memberListBean != null) {
            tv_member_num.setText(String.format(num, memberListBean.size()));
            memberListAdapter.setNewInstance(memberListBean);
        }

        edt_input_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                initTeamGroupAll(s.toString());
            }
        });
    }


    private void initEvent() {
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type != TYPE_MANAGER) {
                    if (!TextUtils.isEmpty(leaderId) && !TextUtils.isEmpty(userName)) {
                        if (null != onHandOverListener) {
                            onHandOverListener.onHandOver(leaderId, userName);
                        }
                    }
                } else {
                    if (!TextUtils.isEmpty(leaderId) && !TextUtils.isEmpty(userName)) {
                        if (kickOut != null) {
                            kickOut.kickOut(leaderId, userName, headerUrl);
                        }
                    }
                }
            }
        });
        memberListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                memberListAdapter.setPoint(position);
                memberListAdapter.notifyDataSetChanged();
                leaderId = memberListAdapter.getData().get(position).userId;
                headerUrl = memberListAdapter.getData().get(position).headImgUrl;
                userName = memberListAdapter.getData().get(position).nickname;
            }
        });
    }


    public void show() {
//        this.setAnimationStyle(R.style.Animation);
        //防止部分手机底部状态栏与popupWindow重叠
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        this.setAnimationStyle(R.style.AnimationBottomFade);
        //popupWindow底部显示
        this.showAtLocation(((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content), Gravity.CENTER, 0, 0);
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();

        lp.alpha = 0.5f;
        if (lp.alpha == 1) {
            ((Activity) context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            ((Activity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        ((Activity) context).getWindow().setAttributes(lp);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
        lp.alpha = 1f;
        ((Activity) context).getWindow().setAttributes(lp);
    }

    public interface OnHandOverListener {
        void onHandOver(String leaderId, String userName);
    }

    public interface KickOut {
        void kickOut(String userId, String userName, String headerUrl);
    }

    private void initTeamGroupAll(String nickName) {
        if (TextUtils.isEmpty(companyId)) return;
        Map<String, Object> params = new HashMap<>();
        params.put("nickName", nickName);
        params.put("topTenantId", companyId);
        new CompanyAPI().allTeamGroup(params, new BaseResultCallback<AllTeamGroupUserEntity>() {
            @Override
            public void onResponse(AllTeamGroupUserEntity response) {
                if (response.code == 0) {
                    //设置移交军团长 popuwindow 数据
                    List<MemberEntity.DataBean.TeamMemberListBean> memberListBean = new ArrayList<>();
                    for (AllTeamGroupUserEntity.DataBean tenant : response.data) {
                        MemberEntity.DataBean.TeamMemberListBean teamMemberBean = new MemberEntity.DataBean.TeamMemberListBean();
                        teamMemberBean.headImgUrl = tenant.headImgUrl;
                        teamMemberBean.nickname = tenant.nickName;
                        teamMemberBean.userId = tenant.userId;
                        teamMemberBean.createTime = tenant.createTime;
                        teamMemberBean.tinder = tenant.totalTinder;
                        memberListBean.add(teamMemberBean);
                    }
                    memberListAdapter.setNewInstance(memberListBean);
                }
            }
        });
    }

}
